from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone
from Utils.dss.Serializer import serializer

from Core import models
from Core.exception import *
from Apis.response import Response
from Apis import auth

import json


@csrf_exempt
def index(request):
    res = Response()
    res.output['url'] = request.path
    return res.ok("Hello World")


@csrf_exempt  # csrf 豁免
def list(request):
    response = Response()
    data = {
        "session_id": "",
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))

        try:
            auth.session_verify_id_s(data['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        session_info = request.session[data['session_id']]
        user = models.User()
        try:
            user = models.User.objects.get(name=session_info['user_name'])
        except user.DoesNotExist as e:
            return response.error("DoesNotExist", "User [{}] does not exist.".format(session_info['user_name']))

        response.output['accounts'] = serializer(user.accounts)
        response.output['session_info'] = session_info
        return response.ok('get accounts list success!')
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def add(request):
    response = Response()
    data = {
        "session_id": "",
        "name": "",
        "account": "",
        "password": "",
        "notes": ""
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))
        try:
            auth.session_verify_id_s(data['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        try:
            account = models.Account()
            account.name = data.get('name', '')
            account.account = data.get('account', '')
            account.password = data.get('password', '')
            account.notes = data.get('notes', '')
            account.save()

            user = models.User.objects.get(id=request.session[data['session_id']]['id'])
            user.accounts.add(account)
            user.save()
        except Exception as e:
            return response.error(str(e), "add account failed.")
        response.output['account_info'] = serializer(account)
        return response.ok("add account success!")
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def update(request):
    response = Response()
    data = {
        "session_id": "",
        "account_id": "",
        "name": "",
        "account": "",
        "password": "",
        "notes": ""
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))
        try:
            auth.session_verify_id_s(data['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        account = models.Account()
        try:
            account = models.Account.objects.get(id=int(data['account_id']))
            if 'name' in data: account.name = data['name']
            if 'account' in data: account.account = data['account']
            if 'password' in data: account.password = data['password']
            if 'notes' in data: account.notes = data['notes']
            account.save()
        except account.DoesNotExist as e:
            return response.error('DoesNotExist', "account id [{}] not exist.".format(data['account_id']))
        except Exception as e:
            return response.error(str(e), "update account failed.")
        return response.ok("update account[{}] info success!".format(data['account_id']))
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())


@csrf_exempt
def delete(request):
    response = Response()
    data = {
        "session_id": "",
        "account_id": "",
    }
    if request.method == 'POST':
        if len(request.body) == 0:
            return response.error("NullRequest")
        data = json.loads(request.body.decode('utf-8'))
        try:
            auth.session_verify_id_s(data['session_id'], request.session)
        except Exception as e:
            return response.error("PermissionDeny", e)

        account = models.Account()
        try:
            account = models.Account.objects.get(id=int(data['account_id']))
            account.delete()
        except account.DoesNotExist as e:
            return response.error('DoesNotExist', "account id [{}] not exist.".format(data['account_id']))
        except Exception as e:
            return response.error(str(e), "delete account failed.")
        return response.ok("delete account[{}] info success!".format(data['account_id']))
    else:
        response.output['api'] = data
        return response.exception(RequestMethodError())
